package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.ResUtils;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.service.RedisService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivitySpike;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.activity.ActivitySpikeJpa;
import cn.hiapi.shopkeeper.request.CreateOrderRequest;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2022/12/13 0:35
 */
@Service
public class ActivitySpikeService extends AbsActivityService<ActivitySpikeJpa, ActivitySpike, Long> {
    public ActivitySpikeService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }

    @Override
    public ActivityType getActivityType() {
        return ActivityType.SPIKE;
    }

    @Override
    @Transactional
    public BasicEntity saveExpand(long activityId, JSONObject data) {
        ActivitySpike spike = data.toJavaObject(ActivitySpike.class);
        if (spike.getPrice() == null || spike.getPrice().compareTo(BigDecimal.ZERO) <= 0)
            throw new BasicException("秒杀价格错误");
        if (spike.getStockNum() < 1) throw new BasicException("商品数量错误");
        if (StringUtils.isEmpty(spike.getTitle())) {
            throw new BasicException("商品标题错误");
        }
        spike.setAid(activityId);

        return this.save(spike);
    }

    @Override
    @Transactional
    public int deleteByAid(long aid) {
        return ResUtils.getDefault(this.repository.deleteByAid(aid));
    }

    @Override
    @Transactional
    public ActivityOrder createOrder(BasicEntity basic, Activity activity, Map<String, Long> incrementStock, CreateOrderRequest request, Token<Object> token) {
        ActivitySpike spike = (ActivitySpike) basic;
        if (spike.getLimitNum() != null && spike.getLimitNum() > 0) {
            long count = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(
                    new QueryWrapper().eq("aid", activity.getId())
                            .eq("buyerId", token.getFid())
                            .eq("statusType", 1).eq("activityType", activity.getType())
            );
            if (count >= spike.getLimitNum())
                throw new BasicException("超过限购数量");
        }
        //库存总数
        final int stockNum = spike.getStockNum();
        long total = this.dispatchContext.getServiceOne(ProductNumService.class).totalByGid(activity.getId(), AppConst.ACTIVITY_SELL_TOTAL);
        long increment = this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 0L);
        if ((total + increment) >= stockNum) {
            throw new BasicException("已被秒杀完");
        }
        this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 1L);

        incrementStock.put(AppConst.ACTIVITY_STOCK_LOCK, activity.getId());
        ActivityOrder order = new ActivityOrder();
        if (request.getSugar() != null)
            order.setSugar(request.getSugar());
        order.setPrice(spike.getPrice());
        order.setCostPrice(activity.getPrice());
        return order;
    }

    @Override
    public BigDecimal sugarDeduction(Activity activity, BigDecimal rate, BigDecimal amount, long uid) {
        ActivitySpike spike = super.getByAid(activity.getId());

        return super.sugarDeduction(spike.getPrice(), rate, amount);
    }


}
